package cn.pping.org.service.impl;

import cn.pping.basic.service.impl.BaseServiceImpl;
import cn.pping.basic.utils.PageList;
import cn.pping.org.domain.Department;
import cn.pping.org.domain.Employee;
import cn.pping.org.mapper.DepartmentMapper;
import cn.pping.org.query.DepartmentQuery;
import cn.pping.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
// 只读事务
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;



    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        String dirPath = "";
        if (department.getParent().getId() == null) {
            dirPath = "/" + department.getId();
        } else {
            Department deptt = departmentMapper.loadById(department.getParent().getId());
            dirPath = deptt.getDirPath() + "/" + department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        String dirPath = "";
        if (department.getParent().getId() == null) {
            dirPath = "/" + department.getId();
        } else {
            Department deptt = departmentMapper.loadById(department.getParent().getId());
            dirPath = deptt.getDirPath() + "/" + department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }




    @Override
    public List<Department> findTree() {
        // 查询这个的全部
        List<Department> departments = departmentMapper.loadAll();
        // 创建一个新集合装入id
        Map<Long, Department> allMap = departments.stream().collect(Collectors.toMap(Department::getId, item -> item));
        // 遍历获取到的每个数据 获取ID判断它是否为空
        List<Department> depts = new ArrayList<>();
        for (Department pare : departments) {
            if (pare.getParent_id()== null) {
                depts.add(pare);
            } else {
                Department department = allMap.get(pare.getParent_id());
                if (department != null) {
                    department.getChildren().add(pare);
                }
            }
        }

        return depts;
    }


    @Override
    public void batch(List<Long> ids) {
        departmentMapper.batch(ids);
    }
}
